package org.sxm.cloud.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Service;
import org.sxm.cloud.dao.UserDao;
import org.sxm.cloud.dto.auth.TokenDTO;
import org.sxm.cloud.entity.order.UserEntity;
import org.sxm.cloud.exception.BizException;
import org.sxm.cloud.service.IAuthService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author xmSheng
 * @Date 2024/3/5
 */

@Service("authService")
public class AuthService implements IAuthService {

    @Resource
    private UserDao userDao;

    private final static String SECRET = "lIjpbImFsbCJdLCJleHAiOjE2MjQwMDQ4MjIsInVzZXJJZCI6MSwiYXV0aG9yaXRpZXMiOlsiUk9MRV_op5Loib";


    @Override
    public TokenDTO login(String account, String password) {
        System.out.println(".........打印进入");
        //校验登录用户信息是否存在
        final UserEntity userEntity = userDao.findByAccount(account);
        if(ObjectUtil.isNull(userEntity)){
            throw new BizException("登录用户信息不存在");
        }
        //校验密码是否正确
        if(!userEntity.getPassword().equalsIgnoreCase(password)){
            throw new BizException("密码错误");
        }
        //生成登录认证凭证
        Map<String, Object> payload = new HashMap<>();
        DateTime now = DateTime.now();
        payload.put(JWTPayload.EXPIRES_AT, now.offset(DateField.SECOND, 60 * 30));  //有效期半小时
        payload.put("uid", userEntity.getId()); //设置用户给UID
        //创建TOKEN
        String token = JWTUtil.createToken(payload, SECRET.getBytes());
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token);
        tokenDTO.setUser(userEntity);
        return tokenDTO;
    }

    @Override
    public UserEntity verifyToken(String token) {
        //用户登录TOKEN不能为空
        if(StrUtil.isBlank(token)){
            throw new BizException("用户登录认证信息不能为空");
        }
        //校验touke是否有效
        JWT jwt = JWTUtil.parseToken(token).setKey(SECRET.getBytes());
        if (!jwt.verify()) { //校验TOKEN是否正确
            throw new BizException("login_error", "用户未登录，请先登录");
        }
        if (!jwt.validate(0)) { //检查TOKEN过期时间
            throw new BizException("login_out_time", "用户登录已过期,请重新登录");
        }
        Integer userId = Integer.parseInt(jwt.getPayload("uid").toString()); //获取用户ID
        Assert.isTrue(userId != null, "用户认证信息异常");
        return userDao.getById(userId);
    }

}
